package com.kidala.algorithms;

public class TreeStructure {

    public static void main(String[] args) {
        Node a = new Node("A");
        Node b = new Node("B");
        a.setLeft(b);
        Node c = new Node("C");
        a.setRight(c);
        c.setLeft(new Node("D"));
        Node e = new Node("E");
        c.setRight(e);
        e.setLeft(new Node("F"));
        Node g = new Node("G");
        e.setRight(g);
        g.setLeft(new Node("H"));
        g.setRight(new Node("I"));

        Node j = new Node("J");
        b.setLeft(j);
        Node k = new Node("K");
        j.setLeft(k);
        Node l = new Node("L");
        k.setLeft(l);
        Node ll = new Node("Ł");
        l.setRight(ll);
        ll.setLeft(new Node("M"));
        ll.setRight(new Node("N"));

        int height = postorder(a, 0);
        System.out.println(height);
    }

    private static int preorder(Node root, int level) {
        System.out.println(root.getName() + " - " + level);
        Node left = root.getLeft();
        Node right = root.getRight();
        int leftlevel = level;
        int rightlevel = level;
        if (left != null) {
            leftlevel = preorder(left, level + 1);
        }
        if (right != null) {
            rightlevel = preorder(right, level + 1);
        }
        if (leftlevel > level) {
            level = leftlevel;
        }
        if (rightlevel > level) {
            level = rightlevel;
        }
        return level;
    }

    private static int postorder(Node root, int level) {
        Node left = root.getLeft();
        Node right = root.getRight();
        int leftlevel = level;
        int rightlevel = level;
        if (left != null) {
            leftlevel = postorder(left, level + 1);
        }
        if (right != null) {
            rightlevel = postorder(right, level + 1);
        }
        System.out.println(root.getName() + " - " + level);
        if (leftlevel > level) {
            level = leftlevel;
        }
        if (rightlevel > level) {
            level = rightlevel;
        }
        return level;
    }

}
